package cn.itlaobing.eshop.web.servlet;


import cn.itlaobing.eshop.entity.Userinfo;
import cn.itlaobing.eshop.exception.BusinessException;
import cn.itlaobing.eshop.service.UserService;
import cn.itlaobing.eshop.web.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:
 * @Author: WangDong
 * @Date: 2017/11/17 19:32
 */

@WebServlet("/user/*")
public class RegisterLoginServlet extends BaseServlet {
    @RequestMapping("/register")
    public void register(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException{
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        Userinfo userinfo=new Userinfo();
        userinfo.setUsername(username);
        userinfo.setUserpass(password);
        UserService userService=new UserService();
        int r=0;
        try {
            r=userService.register(userinfo);
        } catch (BusinessException e) {
            e.printStackTrace();
        }
        if(r<0){
            request.getRequestDispatcher("/WEB-INF/views/members/register.jsp").forward(request,response);
            return;
        }
        //request.getRequestDispatcher("/reglogin/login").forward(request,response);
        response.sendRedirect(request.getContextPath()+"/reglogin/login");

    }
    @RequestMapping("/login")
    public void login(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        UserService userService=new UserService();
        try {
            Userinfo userinfo=userService.findByUser(username,password);
            if(userinfo==null){
                request.setAttribute("MSG","用户名或密码错误！");
                request.getRequestDispatcher("/WEB-INF/views/members/register.jsp").forward(request,response);
                return;
            }
            request.getSession().setAttribute("USER",userinfo);
            request.getRequestDispatcher("/index.jsp").forward(request,response);
        } catch (BusinessException e) {
            e.printStackTrace();
        }

    }





}
